package db

import (
	"context"
	v1 "goTong/app/goods/srv/internal/data/v1"
	"goTong/app/goods/srv/internal/domain/do"
	code2 "goTong/gtong/code"
	metav1 "goTong/pkg/common/meta/v1"
	"goTong/pkg/errors"
	"gorm.io/gorm"
)

type categoryBrands struct {
	db *gorm.DB
}

func (c categoryBrands) List(ctx context.Context, opts metav1.ListMeta, orderby []string) (*do.GoodsCategoryBrandList, error) {
	ret := &do.GoodsCategoryBrandList{}
	//分页
	var limit, offset int
	if opts.PageSize == 0 {
		limit = 10
	} else {
		limit = opts.PageSize
	}
	if opts.Page > 0 {
		offset = (opts.Page - 1) * limit
	}
	//排序
	query := c.db.Preload("Category").Preload("Brands")
	for _, value := range orderby {
		//坑：如果db改掉了？
		//u.db=u.db.Order(value)
		query = query.Order(value)
	}
	//查询 - 发起多个请求
	d := query.Offset(offset).Limit(limit).Find(&ret.Items).Count(&ret.TotalCount)
	if d.Error != nil {
		return nil, errors.WithCode(code2.ErrDatabase, d.Error.Error())
	}
	return ret, nil
}

func (c categoryBrands) Create(ctx context.Context, txn *gorm.DB, gcb *do.GoodsCategoryBrandDO) error {
	tx := c.db.Create(gcb)
	if tx.Error != nil {
		return errors.WithCode(code2.ErrDatabase, tx.Error.Error())
	}
	return nil
}

func (c categoryBrands) Update(ctx context.Context, txn *gorm.DB, gcb *do.GoodsCategoryBrandDO) error {
	tx := c.db.Save(gcb)
	if tx.Error != nil {
		return errors.WithCode(code2.ErrDatabase, tx.Error.Error())
	}
	return nil
}

func (c categoryBrands) Delete(ctx context.Context, ID uint64) error {
	return c.db.Where("id = ?", ID).Delete(&do.GoodsDO{}).Error
}

var _ v1.GoodsCategoryBrandStore = &categoryBrands{}
